package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.selectapply

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.IApiProcessCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.doPostRequest
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.user.mainProcessFormat
import org.json.JSONObject

class SelectApplyGhanaViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _mainProcessResult = MutableLiveData<SelectApplyGhanaMainProcessResult>()
    val mainProcessResult: LiveData<SelectApplyGhanaMainProcessResult> = _mainProcessResult

    private val _nextRouterResult =
        MutableLiveData<SelectApplyGhanaNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<SelectApplyGhanaNextRouterResult<AppCompatActivity>> =
        _nextRouterResult

    /** 查询主流程接口 */
    fun mainProcess() {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj")
                _mainProcessResult.value = SelectApplyGhanaMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _mainProcessResult.value = SelectApplyGhanaMainProcessResult(error = errMsg)
            }
        })

    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormat(fromProof = true)
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                SelectApplyGhanaNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }
}

